﻿using System.Web.Mvc;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System.Threading.Tasks;
using Autofac;
using System.Linq;
using Pay.Service;
using System;

namespace Pay.Web.Areas.Admin.Controllers {
	[RouteArea("admin")]
	[RoutePrefix("merchant")]
	public class MerchantController : AdminController {
		private IMerchantService _iMerchantService;
		private ISettingService _iSettingService;
		private IComponentContext _iocContext;

		public MerchantController(IComponentContext iocContext, IMerchantService iMerchantService, ISettingService iSettingService) {
			_iocContext = iocContext;
			_iMerchantService = iMerchantService;
			_iSettingService = iSettingService;
		}

		public ActionResult Index() {
			return View();
		}

		public JsonResult Gets(MerchantQuery query) {
			var model = _iMerchantService.GetMerchant(query);
			return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
		}

		public JsonResult GetOem() {
			var model = _iMerchantService.GetOems();
			return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
		}

		public JsonResult Get(long id) {
			var model = _iMerchantService.GetMerchant(id);
			return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public JsonResult Add(register_model dto) {
			var result = _iMerchantService.Register(dto);
			return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public JsonResult ChangePwd(forget_model dto) {
			var result = _iMerchantService.Forget(dto);
			return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		public JsonResult Update(merchant_info dto) {
			var user = _iMerchantService.Get(dto.id);
			if (!string.IsNullOrEmpty(dto.parent_no)) {
				var parent = _iMerchantService.Get(dto.parent_no);
				if (parent == null)
					return Json(ResultToJson.Json<int>("上级商户不存在"), JsonRequestBehavior.AllowGet);
				if (user.parent_id != parent.id) {
					dto.parent_id = parent.id;
				}
			} else
				dto.parent_id = 0;
			int result = _iMerchantService.Update(dto);
			return Json(ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
		}

		[HttpDelete]
		public JsonResult Detele(long id) {
			int result = _iMerchantService.Delete(id);
			return Json(ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 启用/禁用
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Disable(long id, bool disabled) {
			var user = _iMerchantService.GetMerchant(id);
			user.disabled = disabled;
			int result = _iMerchantService.Update(user);
			return Json(ResultToJson.Json(result > 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 审核认证
		/// </summary>
		/// <returns>The audit.</returns>
		/// <param name="id">Identifier.</param>
		/// <param name="auth_info">Auth info.</param>
		/// <param name="status">Status.</param>
		/// <param name="msg">Message.</param>
		[HttpPost]
		public async Task<JsonResult> Audit(long id, auth_info_setting auth_info, AuthStatusEnum status, string msg) {
			int result = await _iMerchantService.Auth(id, auth_info, status, msg);
			return Json(ResultToJson.Json(result >= 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 审核认证
		/// </summary>
		/// <returns>The audit.</returns>
		/// <param name="id">Identifier.</param>
		/// <param name="status">Status.</param>
		/// <param name="msg">Message.</param>
		[HttpPost]
		public async Task<JsonResult> WXAudit(long id, AuthStatusEnum status, string msg) {
			int result = await _iMerchantService.AuthNative(id, status, msg);
			return Json(ResultToJson.Json(result >= 0 ? " 保存成功" : "保存失败", result), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 修改认证资料
		/// </summary>
		/// <returns>The audit.</returns>
		/// <param name="id">Identifier.</param>
		/// <param name="auth_info">Auth info.</param>
		[HttpPost]
		public async Task<JsonResult> AuthEdit(long id, auth_info_setting auth_info) {
			int result = await _iMerchantService.AuthEdit(id, auth_info);
			return Json(ResultToJson.Json(result >= 0 ? " 修改认证资料成功" : "修改认证资料失败", result), JsonRequestBehavior.AllowGet);
		}


        /// <summary>
        /// 查询认证资料
        /// </summary>
        /// <returns>The register del.</returns>
        /// <param name="id">Identifier.</param>
        public JsonResult AuthList(MemberQuery query) {
            var list = _iMerchantService.Get(query);
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 商户进件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
		public async Task<JsonResult> AddMerchant(long id, PayChannel pay_channel, string settle_type, string account_no) {
			var binder = _iMerchantService.Get(id);
			merchant_register_model model = null;
			var _iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
			var oemer = _iMerchantService.Get(binder.oem_id.Value);
            var oemer_payments = _iMerchantService.GetPayments(oemer.id);
            var oem_payment = oemer_payments.FirstOrDefault(c => c.payment.channel == pay_channel && c.payment.is_register);
			if (oem_payment != null) {
                var binder_registers = _iMerchantService.GetRegisters(binder.id);
                var binder_payments = _iMerchantService.GetPayments(binder.id);
                //判断是否进件过了
                merchant_register_dto register = null;
				if (oem_payment.payment.is_more)
					register = binder_registers.FirstOrDefault(c => c.pay_channel == pay_channel && c.settle_type == settle_type && c.account_no == account_no);
				else
					register = binder_registers.FirstOrDefault(c => c.pay_channel == pay_channel && c.settle_type == settle_type);
				string opt = "A";
				if (register != null) {
					opt = "M";
					model = register.ToDtoObject<merchant_register_model>();
					model.reg_merchant_no = register.merchant_no;
				} else {
					model = binder.setting.auth_info.ToDtoObject<merchant_register_model>();
					if (pay_channel == PayChannel.HxData) {
						model.reg_merchant_no = binder.merchant_no;
						model.reg_mobile = 130 + DtoHelper.RandCode(8);
					}
				}
				model.pay_channel = pay_channel;
				model.settle_type = settle_type;
				model.bind_no = binder.merchant_no;
				model.merchant_no = oemer.merchant_no;

				var payment = binder_payments.FirstOrDefault(c => c.payment.channel == pay_channel && c.payment.is_register);
				var settle = payment.settles.FirstOrDefault(c => c.settle_type == settle_type);
				model.fee = settle.fee;
				model.settle = ((int)(settle.settle * 100)).ToString();
				var result = await _iPayService.MerchantRegister(model, opt);
				if (result.result_code == 1000) {
					_iMerchantService.MerchantChannelRegister(model);
					return Json(ResultToJson.Json("保存成功", result.merchant_no), JsonRequestBehavior.AllowGet);
				}
				return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
			}
			return Json(ResultToJson.Json<string>("oem商户没有开通"), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 用实名数据进件
		/// </summary>
		/// <returns>The register.</returns>
		/// <param name="id">Identifier.</param>
		/// <param name="pay_channel">Pay channel.</param>
		/// <param name="settle_type">Settle type.</param>
		/// <param name="op">Op.</param>
		public async Task<JsonResult> AuthRegister(long id, PayChannel pay_channel, string settle_type, string op) {
			var binder = _iMerchantService.Get(id);
			merchant_register_result result = null;
			var _iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
            var binder_payments = _iMerchantService.GetPayments(binder.id);
            if (binder_payments.Any(c => c.payment.channel == pay_channel && c.payment.is_more))
				return Json(ResultToJson.Json("多进件模式不可以用实名提交", result.merchant_no), JsonRequestBehavior.AllowGet);

            var binder_registers = _iMerchantService.GetRegisters(binder.id);
            if (binder_registers.Any(c => c.pay_channel == pay_channel && c.settle_type == settle_type) || (!string.IsNullOrEmpty(op) && op == "M"))
				result = await _iPayService.MerchantModify(id, settle_type,pay_channel);
			else
				result = await _iPayService.MerchantRegister(id, settle_type,pay_channel);
			if (result.result_code == 1000)
				return Json(ResultToJson.Json("保存成功", result.merchant_no), JsonRequestBehavior.AllowGet);
			return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 删除进件
		/// </summary>
		/// <returns>The register del.</returns>
		/// <param name="id">Identifier.</param>
		public JsonResult auth_register_del(long id) {
			var result = _iMerchantService.DeleteMerchantRegister(id);
			if (result > 0)
				return Json(ResultToJson.Json<bool>("删除成功", result > 0), JsonRequestBehavior.AllowGet);
			return Json(ResultToJson.Json<bool>("删除失败"), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 验证实名
		/// </summary>
		/// <returns>The verifyed.</returns>
		/// <param name="id">Identifier.</param>
		public async Task<JsonResult> CertifyVerifyed(long id) {
			var merchant = _iMerchantService.Get(id);
			var model = merchant.setting.auth_info;
			var oemer = _iMerchantService.Get(merchant.parent_id);
			var certify = _iSettingService.Get().certify;
			var cer = certify.FirstOrDefault(c => c.merchant_no == oemer.merchant_no);
			if (merchant.auth_status == AuthStatusEnum.Wait) {
				var reqData = new certify_verify {
					merchant_no = oemer.merchant_no, amount = cer.amount, bank_code = model.bank_code,
					account_name = model.account_name, account_no = model.account_no, id_card = model.id_card,
					verify_type = "0030", mobile = model.mobile, bind_no = merchant.merchant_no, card_type = 1,
					order_no = DateTime.Now.ToString("yyyyMMddHHmmssffff") + DtoHelper.RandCode(6), pay_channel = cer.pay_channel
				};
				var iPayService = _iocContext.ResolveKeyed<IPayService>(cer.pay_channel);
				var api_result = await iPayService.CertifyVerify(reqData);
				if (api_result.result_code == 1000)
					return Json(ResultToJson.Json("实名成功", true), JsonRequestBehavior.AllowGet);
				return Json(ResultToJson.Json<bool>(api_result.result_msg), JsonRequestBehavior.AllowGet);
			}
			return Json(ResultToJson.Json<bool>("OEM没有开通实名"), JsonRequestBehavior.AllowGet);
		}
	}
}